package com.yjk1.example.myFirstSofawebBoot;

import com.yjk1.example.myFirstSofawebBoot.classloader.PluginClassLoader;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yujiakui
 * @version 1.0
 * Email: jkyu@haiyi-info.com
 * date: 2018/11/12 10:26
 * description：
 **/
public class MyBizPluginManager {

    private Map<String ,PluginClassLoader> pluginMap = new HashMap<String,PluginClassLoader>();

    private void addLoader(String pluginName,PluginClassLoader loader){
        this.pluginMap.put(pluginName, loader);
    }
    private PluginClassLoader getLoader(String pluginName){
        return this.pluginMap.get(pluginName);
    }
    public void loadPlugin(String pluginPath,String pluginName,ClassLoader parentClassLoader){
        this.pluginMap.remove(pluginName);
        PluginClassLoader loader = new PluginClassLoader(parentClassLoader);

        List<URL> allJarUrls = null;
        try {
            allJarUrls = findDependencyJar(pluginPath);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        for (URL jarUrl:allJarUrls) {
            loader.addURLFile(jarUrl);
        }

        addLoader(pluginName, loader);
        System.out.println("load " + pluginName + "  success");
    }
    public void unloadPlugin(String pluginName){
        this.pluginMap.get(pluginName).unloadJarFiles();
        this.pluginMap.remove(pluginName);
    }

    private static List<URL> findDependencyJar(String pluginPath) throws MalformedURLException {
        File file = new File(pluginPath);
        List<URL> list = new ArrayList<>();
        File parentFile = file.getParentFile();
        File libFile = new File(file.getParent() + File.separator + "lib");
        if (libFile.exists() && parentFile.isDirectory()) {
            for (File jar : libFile.listFiles()) {
                if (jar.isFile()
                        && jar.getName().toLowerCase().endsWith(".jar")
                        ) {
                    list.add(new URL("jar:file:/"+jar.getPath()+"!/"));
                }
            }
        }
        list.add(new URL("jar:file:/"+pluginPath+"!/"));
        return list;

    }

    public URLClassLoader getClassLoaderByPluginName(String pluginName){
        return this.pluginMap.get(pluginName);
    }
}
